package com.usooft.metaTalent.core.platform.service.base;

import com.usooft.framework.core.query.Limit;
import com.usooft.framework.core.query.Page;
import com.usooft.metaTalent.core.platform.entity.Tag;
import com.usooft.metaTalent.core.platform.mapper.TagMapper;
import com.usooft.metaTalent.core.platform.query.TagQuery;
import com.usooft.metaTalent.core.platform.service.TagService;
import com.usooft.metaTalent.core.platform.wrapper.TagWrapper;
import java.lang.Long;
import java.lang.Override;
import java.lang.String;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.OptimisticLockingFailureException;
import org.springframework.lang.NonNull;

public abstract class BaseTagService implements TagService {
    @Autowired
    private TagMapper tagMapper;

    @Override
    public Tag get(@NonNull Long id) {
        return find(id).orElseThrow();
    }

    @Override
    public Optional<Tag> find(@NonNull Long id) {
        return Optional.ofNullable(tagMapper.get(id));
    }

    @Override
    public List<TagWrapper> list(TagQuery query) {
        return tagMapper.list(query);
    }

    @Override
    public Page<TagWrapper> page(TagQuery query) {
        int rows = tagMapper.count(query.getFilter());
        return new Page<>(rows, rows == 0 ? new ArrayList<>() : tagMapper.list(query));
    }

    protected Optional<Tag> findOne(TagQuery.Filter filter, TagQuery.Sorts sorts) {
        List<TagWrapper> wrappers = list(TagQuery.builder()
                                .filter(filter)
                                .sorts(sorts)
                                .limit(Limit.rowCount(1))
                                .build());
        return wrappers.stream().findFirst().map(Function.identity());
    }

    protected Optional<Tag> findOne(TagQuery.Filter filter) {
        return findOne(filter, TagQuery.Sorts.builder().build());
    }

    @Override
    public int count(TagQuery.Filter filter) {
        return tagMapper.count(filter);
    }

    protected Tag internalAdd(String name) {
        Tag tag = new Tag();
        tag.setName(name);

        tag.setCreatedDate(LocalDateTime.now());
        tag.setVersion(0);
        tag.setIsDelete(false);
        tagMapper.add(tag);
        return tag;
    }

    protected void internalUpdate(@NonNull Tag tag) {
        tag.setLastModifiedDate(LocalDateTime.now());

        int rows = tagMapper.update(tag);
        if (rows == 0) {
            throw new OptimisticLockingFailureException("更新失败。可能标签 (" + tag.getId() + ") 的版本 (" + tag.getVersion() + ") 已不是最新");
        }
        tag.setVersion(tag.getVersion() + 1);
    }
}
